<template>
  <div class="app-container">
    <!-- 添加或修改设备对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="人员"
      :visible.sync="show"
      @on-cancel="show = false"
      width="1200px"
      @open="onOpen"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="车牌号" prop="carNum">
          <el-input
            v-model="queryParams.carNum"
            placeholder="请输入车牌号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <el-select
            v-model="queryParams.carType"
            placeholder="请选择车辆类型"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in dict.type.base_car_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="carList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="车牌号"
          align="left"
          prop="carNum"
          minWidth="120px"
        />
        <el-table-column
          label="车辆类型"
          align="left"
          prop="carType"
          width="120px"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.base_car_type"
              :value="scope.row.carType"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="车辆所属权"
          align="left"
          prop="carAttribution"
          width="120px"
        />
        <el-table-column
          label="发动机号"
          align="left"
          prop="engineNum"
          width="150px"
        />
        <el-table-column
          label="车架号"
          align="left"
          prop="frameNum"
          width="180px"
        />
        <el-table-column
          label="车辆照片"
          align="left"
          prop="photoPath"
          width="100"
        >
          <template slot-scope="scope">
            <i
              v-if="scope.row.photoPath"
              class="el-icon-view"
              style="cursor: pointer; color: #1890ff"
              @click="handleViewPic(scope.row.photoPath)"
            ></i>
          </template>
        </el-table-column>
        <el-table-column
          label="购入日期"
          align="left"
          prop="buyDate"
          width="100"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.buyDate, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">提 交</el-button>

        <el-button @click="show = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCar, getCar } from "@/api/base/car";

export default {
  name: "carDialog",
  dicts: ["base_car_type"],
  props: {
    visible: {
      type: Boolean,
      default: function () {
        return false;
      },
    },
    hasSelect: {
      required: true,
      default: [],
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员表格数据
      carList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carType: null,
        carNum: null,

        bind: 1,
      },
      tableSelectRows: [], //表格select复选框选中的id
    };
  },
  computed: {
    show: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  created() {
    this.getList();
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("car_type").then((response) => {
      this.carTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询人员列表 */
    getList() {
      this.loading = true;
      listCar(this.queryParams).then((response) => {
        this.carList = response.rows;
        this.total = response.total;
        // 回显选中
        this.$nextTick(() => {
          let rows = [];
          this.carList.forEach((row) => {
            this.tableSelectRows.forEach((item) => {
              if (row.carId === item.carId) {
                rows.push(row);
              }
            });
          });
          this.toggleSelection(rows);
        });
        this.loading = false;
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      } else {
        this.resetSelect();
      }
    },
    resetSelect() {
      //清空选择
      this.$refs["multipleTable"].clearSelection();
    },
    // 性别字典翻译
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex);
    },
    // 人员类型字典翻译
    carTypeFormat(row, column) {
      return this.selectDictLabel(this.carTypeOptions, row.carType);
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      //选择
      if (selection.length === 0 && this.carList !== null) {
        //若是全不选，则循环删除selected数组中存在的项
        this.carList.forEach((item) => {
          this.handleDelItem(item);
        });
      } else {
        // 全选，将selected和当前table数据合起来，注意去重！
        if (selection && selection.length > 0) {
          selection.forEach((row) => {
            let tempRow = JSON.parse(JSON.stringify(row));
            this.tableSelectRows.push(tempRow);
          });
          // 数组去重
          let newData = {};
          this.tableSelectRows = this.tableSelectRows.reduce(
            (preVal, curVal) => {
              newData[curVal.carId]
                ? ""
                : (newData[curVal.carId] = true && preVal.push(curVal));
              return preVal;
            },
            []
          );
        }
      }
    },
    handleDelItem(row) {
      let index = -1;
      this.tableSelectRows.forEach((item, idx) => {
        if (item.carId === row.carId) {
          index = idx;
        }
      });
      if (index >= 0) {
        this.tableSelectRows.splice(index, 1);
      }
    },
    submit() {
      this.$emit("changeCars", this.tableSelectRows);
      this.show = false;
    },
    onOpen() {
      this.tableSelectRows = JSON.parse(JSON.stringify(this.hasSelect));

      this.getList();
    },
  },
};
</script>
